package com.javasm.gg.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.javasm.commons.util.SpringUtil;
import com.javasm.dict.entity.SysDicData;
import com.javasm.dict.service.DicDataService;
import com.javasm.dict.service.impl.DicDataServiceImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProductColorConverter implements Converter<Integer> {
    private static DicDataService dds;
    private Map<String,Integer> colorLabel = new HashMap<>();
    private Map<Integer,String> colorVal = new HashMap<>();

    @Override
    public Integer convertToJavaData(ReadConverterContext<?> context) throws Exception {
        init();
        String stringValue = context.getReadCellData().getStringValue();
        return colorLabel.get(stringValue);
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) throws Exception {
        init();
        Integer value = context.getValue();
        return new WriteCellData<>(colorVal.get(value));
    }

    private void init(){
        if (dds==null){
            dds = SpringUtil.getBean(DicDataServiceImpl.class);
            SysDicData sd = new SysDicData();
            sd.setDicType("phone_color");
            List<SysDicData> list = dds.getList(sd);
            for (SysDicData s : list) {
                colorLabel.put(s.getDicDataLabel(),s.getDicDataVal());
            }
            for (SysDicData s : list) {
                colorVal.put(s.getDicDataVal(),s.getDicDataLabel());
            }
        }
    }
}
